<template>
    <div>
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>用户管理</el-breadcrumb-item>
            <el-breadcrumb-item>用户列表</el-breadcrumb-item>
        </el-breadcrumb>
        <el-card class="box-card">
            <el-row :gutter="20">
                <el-col :span="7">
                    <el-input placeholder="请输入内容" v-model="userParam.query" :clearable="true" @clear="getUserList">
                        <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
                    </el-input>
                </el-col>
                <el-col :span="4">
                    <el-button type="primary" @click="openDialog">添加用户</el-button>
                </el-col>
            </el-row>
            <el-row>
                <el-table stripe :data="userList" border style="width: 100%">
                    <el-table-column type="index"></el-table-column>
                    <el-table-column prop="username" label="姓名"></el-table-column>
                    <el-table-column prop="email" label="邮箱"></el-table-column>
                    <el-table-column prop="mobile" label="电话"></el-table-column>
                    <el-table-column prop="role_name" label="角色"></el-table-column>
                    <el-table-column prop="mg_state" label="状态">
                        <template slot-scope="scope">
                            <el-switch v-model="scope.row.mg_state" @change="userStateChanged(scope.row)">
                            </el-switch>
                        </template>
                    </el-table-column>
                    <el-table-column label="操作">
                        <template slot-scope="scope">
                            <el-button type="primary" icon="el-icon-edit" size="mini" @click="editUser(scope.row.id)"></el-button>
                            <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteUser(scope.row.id)"></el-button>
                            <el-tooltip class="item" effect="dark" content="分配角色" placement="top" :enterable="false">
                                <el-button type="warning" icon="el-icon-setting" size="mini" @click="assignRoleDialog(scope.row)"></el-button>
                            </el-tooltip>
                        </template>
                    </el-table-column>
                </el-table>
                <el-pagination
                        @size-change="handleSizeChange"
                        @current-change="handleCurrentChange"
                        :current-page="userParam.pagenum"
                        :page-sizes="[1, 2, 5, 10]"
                        :page-size="userParam.pagesize"
                        layout="total, sizes, prev, pager, next, jumper"
                        :total="total">
                </el-pagination>
            </el-row>
        </el-card>
        <!--添加用户对话框-->
        <el-dialog title="添加用户" :visible.sync="dialogVisible" width="50%" @close="addFormRulesClose">
            <!--内容主体-->
            <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="70px">
                <el-form-item label="用户名" prop="username">
                    <el-input v-model="addForm.username"></el-input>
                </el-form-item>
                <el-form-item label="密码" prop="password">
                    <el-input v-model="addForm.password"></el-input>
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                    <el-input v-model="addForm.email"></el-input>
                </el-form-item>
                <el-form-item label="手机" prop="phone">
                    <el-input v-model="addForm.phone"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="addUser()">确 定</el-button>
             </span>
        </el-dialog>
        <!--修改用户对话框-->
        <el-dialog
                title="修改用户"
                :visible.sync="editDialogVisible"
                width="30%"
                @close="closeEditUser">
            <el-form ref="editUserRef" :model="editUserForm" :rules="editFormRules" label-width="80px">
                <el-form-item label="姓名">
                <el-input v-model="editUserForm.username" disabled></el-input>
            </el-form-item>
                <el-form-item label="邮箱" prop="email">
                    <el-input v-model="editUserForm.email"></el-input>
                </el-form-item>
                <el-form-item label="电话" prop="mobile">
                    <el-input v-model="editUserForm.mobile"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
    <el-button @click="editDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="editUserInfo">确 定</el-button>
  </span>
        </el-dialog>
<!--        分配角色对话框-->
        <el-dialog title="分配角色" :visible.sync="rolesDialogVisible" width="50%" @close="rolesDialogClose">
            <p>当前用户：{{this.role.username}}</p><br>
            <p>当前角色：{{this.role.role_name}}</p><br>
            <p>当前分配的新角色：
                <el-select v-model="selectRoleId" placeholder="请选择" size="mini">
                    <el-option
                            v-for="item in roleList"
                            :key="item.id"
                            :label="item.roleName"
                            :value="item.id">
                    </el-option>
                </el-select>
            </p>
                <span slot="footer" class="dialog-footer">
                    <el-button @click="rolesDialogVisible = false">取 消</el-button>
                    <el-button type="primary" @click="assignRole">确 定</el-button>
                </span>
        </el-dialog>
    </div>
</template>

<script>
    export default {
        name: "users",
        data() {
            //验证邮箱的规则
            const checkEmail = (rule, value, callback) => {
                //验证邮箱的正则表达式
                const regEmail= /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/
                if(regEmail.test(value)){return callback()}
                callback(new Error('请输入合法的邮箱'))
            };
            //验证手机号规则
            const checkMobile=(rule,value,cb)=>{
                //验证手机号的正则表达式
                const regMobile=/^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/
                if(regMobile.test(value)){
                    return cb()
                }
                cb(new Error('请输入合法的手机号'))
            };
            return {
                dialogVisible: false,
                editDialogVisible:false,
                userParam: {
                    //搜索关键字
                    query: '',
                    //当前的页数
                    pagenum: 1,
                    //当前每页显示多少条数据
                    pagesize: 2
                },
                userList: [],
                total: 0,
                //添加用户表单
                addForm:{
                    username:'',
                    password:'',
                    email:'',
                    phone:''
                },
                //修改用户表单
                editUserForm:{
                    
                },
                addFormRules:{
                    username: [{required:true,message:'请输入用户名',trigger:'blur'}],
                    password: [{required:true,message:'请输入密码',trigger:'blur'}],
                    email: [{required:true,message:'请输入邮箱',trigger:'blur'},{validator:checkEmail,trigger: 'blur'}],
                    phone: [{required:true,message:'请输入手机号',trigger:'blur'},{validator:checkMobile,trigger: 'blur'}],
                },
                editFormRules:{
                    email: [{required:true,message:'请输入邮箱',trigger:'blur'},{validator:checkEmail,trigger: 'blur'}],
                    mobile: [{required:true,message:'请输入手机号',trigger:'blur'},{validator:checkMobile,trigger: 'blur'}],
                },
                rolesDialogVisible:false,
                //分配角色时的当前角色
                role:{},
                //所有的角色列表
                roleList:[],
                //已选中的role的id值
                selectRoleId:'',
                //分配角色时当前用户的id
                selectUserId:''
            }
        },
        created() {
            this.getUserList()
        },
        methods: {
            getUserList() {
                this.$http.get('users', {params: this.userParam}).then((response) => {
                    if (response.data.meta.status != 200) {
                        return this.$message.error('获取用户列表失败')
                    }
                    this.userList = response.data.data.users
                    this.total = response.data.data.total
                })
            },
            handleSizeChange(pageSize) {
                this.userParam.pagesize = pageSize
                this.getUserList()
            },
            handleCurrentChange(currentSize) {
                this.userParam.pagenum = currentSize
                this.getUserList()
            },
            userStateChanged(userChange) {
                this.$http.put('users/' + userChange.id + '/state/' + userChange.mg_state + '').then((response) => {
                    if (response.data.meta.status == 200) {
                        return this.$message.success("更新用户状态成功")
                    } else {
                        userChange.mg_state = !userChange.mg_state;
                        return this.$message.error("更新用户状态失败")
                    }
                })
            },
            openDialog() {
                this.dialogVisible = true
            },
            //获取所有角色列表
            getRoleList(){
              this.$http.get('roles').then((res)=>{
                  if (res.data.meta.status!==200){
                      this.$message.error('获取角色列表失败')
                  }else {
                      this.roleList=res.data.data
                  }
              })  
            },
            //添加用户
            addUser(){
                this.$refs.addFormRef.validate(valid=>{
                    if (!valid) return
                    //可以发起添加用户的网络请求
                    this.$http.post('users',this.addForm).then((result) => {
                        if (result.data.meta.status==201){
                            this.$message.success('添加成功')
                        }else{
                            console.log(this.addForm)
                            console.log(result)
                            this.$message.error('添加失败')
                        }
                        this.dialogVisible=false
                        this.getUserList()
                    })
                })
            },
            //修改用户
            editUser(id){
                this.editDialogVisible=true
            //    获取选中行的对象数据
                this.$http.get('users/'+id).then((res)=>{
                    this.editUserForm=res.data.data
                })
            },
            closeEditUser(){
                this.$refs.editUserRef.resetFields()
            },
            //修改用户信息并提交
            editUserInfo(){
                this.$refs.editUserRef.validate(valid=>{
                    if (!valid){
                        return
                    }else {
                        this.$http.put('users/'+this.editUserForm.id,{email:this.editUserForm.email,mobile:this.editUserForm.mobile}).then(
                            (res)=>{
                                if (res.data.meta.status==200){
                                    this.$message.success('更新用户信息成功')
                                    this.getUserList()
                                    this.editDialogVisible=false
                                }else {
                                    this.$message.error('更新用户信息失败')
                                }
                            }
                        )
                    }
                })
            },
            //删除用户
            deleteUser(id){
                this.$confirm('此操作将永远删除该用户，是否继续？','提示',{
                    confirmButtonText:'确定',
                    cancelButtonText:'取消',
                    type:'warning'
                }).then(()=>{
                    this.$http.delete("users/"+id).then((res)=>{
                        if (res.data.meta.status==200){
                            this.$message.success('删除用户成功')
                            this.getUserList()
                        }else{
                            this.$message.error('删除用户失败')
                        }
                    })
                }).catch(()=>{
                    this.$message.info('已取消删除')
                })
            },
            //打开分配角色对话框
            assignRoleDialog(user){
                this.role.username=user.username
                this.role.role_name=user.role_name
                this.selectUserId=user.id
                this.getRoleList()
                this.rolesDialogVisible=true
            },
            //  确认分配角色
            assignRole(){
                if (!this.selectRoleId){
                    this.$message.warning('请选择要分配的角色')
                }
                this.$http.put('users/'+this.selectUserId+'/role',{rid:this.selectRoleId}).then((res)=>{
                    if (res.data.meta.status!==200){
                        this.$message.error('分配角色失败')
                    }else {
                        this.$message.success('更新角色成功')
                        this.getUserList()
                        this.rolesDialogVisible=false
                    }
                })
            },
            //分配角色对话框关闭事件
            rolesDialogClose(){
                this.selectRoleId=''
            },
            //监听添加用户对话框关闭事件
            addFormRulesClose(){
                this.$refs.addFormRef.resetFields()
            }
        }
    }
</script>

<style scoped>

</style>
